import SparkMD5 from "spark-md5";
/*
    读取文件的方法
*/
export function read(file) {
  //实例化FileReader对象
  const fileReader = new FileReader();
  return new Promise((resolve, reject) => {
    fileReader.onload = function () {
      resolve(fileReader.result);
    };
    fileReader.onerror = reject;
    fileReader.readAsArrayBuffer(file);
  });
}
/*
    获取文件hash值的方法
*/
export function getSparkHash(content) {
  let spark = new SparkMD5.ArrayBuffer();
  spark.append(content);
  let hash = spark.end();
  return hash;
}

/*
  获取切片数组
  参数1：文件对象
  参数2：hash值
  参数3：切片的大小
*/
export function getChunkList(file,hash,chunkSize) {
  const {name,size}=file
  const chunkList = [];
  const chunkLen = Math.ceil(size / chunkSize);
  const suffix = /\.([0-9A-z]+)/.exec(name)[0];
  let index = 0;
  while (index < chunkLen) {
    chunkList.push({
      chunk: file.slice(index * chunkSize, (index + 1) * chunkSize),
      fileName: `${hash}_${index + 1}${suffix}`,
    });
    index++;
  }
  return chunkList
}
